package com.liyunc.demo.realm;

import com.liyunc.demo.model.entity.Resource;
import com.liyunc.demo.model.entity.Role;
import com.liyunc.demo.model.entity.User;
import com.liyunc.demo.model.repository.ResourceRepository;
import com.liyunc.demo.model.repository.RoleRepository;
import com.liyunc.demo.model.repository.UserRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 自定义过滤规则.
 */
@Slf4j
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private ResourceRepository resourceRepository;


    /**
     * 授权.
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = (String) SecurityUtils.getSubject().getPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Set<String> roles = new HashSet<>();
        List<Role> rolesByUserName = roleRepository.getRolesByUserName(username);
        log.info(username + "拥有的角色有:" + rolesByUserName.toString());
        for (Role role : rolesByUserName) {
            roles.add(role.getName());
        }
        List<Resource> resourcesByUserName = resourceRepository.getResourcesByUserName(username);
        log.info(username + "拥有的权限有:" + resourcesByUserName.toString());
        for (Resource resource : resourcesByUserName) {
            info.addStringPermission(resource.getTitle());
        }
        info.setRoles(roles);
        return info;
    }

    /**
     * 认证.
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
        throws AuthenticationException {
        System.out.println("token.getPrincipal:" + token.getPrincipal());
        System.out.println("token.getCredentials:" + token.getCredentials());
        String userName = token.getPrincipal().toString();
        User user = userRepository.getUserByUsername(userName);
        if (user != null) {
            // Object principal, Object credentials, String realmName
            return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), getName());
        } else {
            return null;
        }
    }
}
